package weaver.interfaces.linearin.duss.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;


public class InvokeHelper {

    public static String POST_K3CloudURL = "http://8.136.106.175/k3cloud";
    private static String sessionkey = "kdservice-sessionid";
    private static String aspnetsessionkey = "ASP.NET_SessionId";
    public static Map map = new HashMap();

    static {
        map.put("Save", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        map.put("View", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        map.put("Query", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
        map.put("Submit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        map.put("Audit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        map.put("UnAudit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        map.put("StatusConvert", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        map.put("Draft", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft.common.kdsvc");
    }

    public static String getUser() {
        JSONObject userInfo = new JSONObject();
        userInfo.put("acctID", "65404b3713a33c");
        userInfo.put("username", "沈斌");
        userInfo.put("password", "abcd.1234");
        userInfo.put("lcid", "2052");
        return userInfo.toString();
    }

    /**
     * 接口调用处理器
     *
     * @param type
     * @param formId
     * @param content
     * @return
     */
    public static JSONObject handleInvoke(String type, String formId, String content) {
        JSONObject resultJson = new JSONObject();
        // 定义httpClient的实例
        HttpClient httpclient = new DefaultHttpClient();
        String code = "success";
        String message = "登录成功";
        String data = "";
        String sessionValue = "";
        String aspnetsessionValue = "";
        try {
            //登录，校验用户的API接口地址
            String Login_URL = POST_K3CloudURL + "/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
            HttpPost method = new HttpPost(new URI(Login_URL));
            StringEntity entity = new StringEntity(getUser(), "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            method.setEntity(entity);
            HttpResponse response = httpclient.execute(method);
            int respCode = response.getStatusLine().getStatusCode();
            if (respCode == 200) {
                // 读取服务器返回过来的json字符串数据
                String str = EntityUtils.toString(response.getEntity());
                // 把json字符串转换成json对象
                JSONObject jsonResult = JSONObject.parseObject(str);
                //判断登录是否成功
                int loginType = jsonResult.getIntValue("LoginResultType");
                if (loginType == 1) {
                    // 获取Cookie
                    Header[] headers = response.getHeaders("Set-Cookie");
                    for (int i = 1; i < headers.length; i++) {
                        Header header = headers[i];
                        String headerValue = header.getValue();
                        // 登录成功返回的登录session信息，保存下来，下面再调用接口的时候传给服务端
                        if (headerValue.trim().startsWith(sessionkey)) {
                            int endIndex = headerValue.indexOf(';');
                            sessionValue = headerValue.substring(20, endIndex);
                        } else if (headerValue.trim().startsWith(aspnetsessionkey)) {
                            int endIndex = headerValue.indexOf(';');
                            aspnetsessionValue = headerValue.substring(18, endIndex);
                        }
                    }
                } else {
                    code = "failure";
                    message = "金蝶登录认证失败，登录状态:" + loginType;
                }
            } else {
                code = "failure";
                message = "金蝶登录认证失败，接口响应码:" + respCode;
            }
            // 请求发送成功，并得到响应
        } catch (Exception e) {
            code = "failure";
            message = "金蝶登录接口异常,请联系管理员";
            System.out.println("金蝶登录接口异常：" + e.getMessage());
        }
        if ("success".equals(code)) {
            try {
                // 数据接口地址
                String url = POST_K3CloudURL + "/" + map.get(type).toString();
                HttpPost method = new HttpPost(new URI(url));
                //保存参数
                JSONObject params = new JSONObject();
                if (!("Query").equals(type)) {
                    params.put("formid", formId);
                }
                params.put("data", content);
                StringEntity entity = new StringEntity(params.toString(), "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                //把成功登录的Session信息传进去，获取连接信息
                method.setHeader(sessionkey, sessionValue);
                method.setHeader(aspnetsessionkey, aspnetsessionValue);
                //方法参数
                method.setEntity(entity);
                HttpResponse response = httpclient.execute(method);
                // 请求发送成功，并得到响应
                int respCode = response.getStatusLine().getStatusCode();
                if (respCode == 200) {
                    // 读取服务器返回过来的json字符串数据
                    data = EntityUtils.toString(response.getEntity());
                    message = "请求业务接口成功";
                } else {
                    code = "failure";
                    message = "请求业务接口异常,接口响应码:" + respCode;
                }
            } catch (Exception e) {
                code = "failure";
                message = "金蝶业务接口异常,请联系管理员";
                System.out.println("金蝶业务接口异常：" + e.getMessage());
            }
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        resultJson.put("data", data);
        return resultJson;
    }

    /**
     * 插入接口日志
     *
     * @param dataMap
     * @param apiType
     */
    private static void insertApiLog(Map<String, Object> dataMap, String apiType) {
        String apiUrl = POST_K3CloudURL + Util.null2String(map.get(apiType));
        String fullDate = DateUtil.getFullDate();
        dataMap.put("jkqqdz", apiUrl);
        dataMap.put("jkdysj", fullDate);
        insertModelData("uf_apilog", 1, dataMap);
    }

    //建模权限重构
    private static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    private static int insertModelData(String tablename, int userid, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        try {
            //查询该模块表名
            String sql = "select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename=?";
            rs.executeQuery(sql, tablename);
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
            if (rs.executeUpdate(insSql, params)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        rs.executeUpdate(updatesql);
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataid;
    }

    // Save 保存
    public static JSONObject Save(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("Save", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "Save");
        return resultJson;
    }

    // View 查看
    public static JSONObject View(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("View", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "View");
        return resultJson;
    }

    // Submit 提交
    public static JSONObject Submit(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("Submit", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "Submit");
        return resultJson;
    }

    // Draft  暂存
    public static JSONObject Draft(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("Draft", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "Draft");
        return resultJson;
    }

    // Audit 审核
    public static JSONObject Audit(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("Audit", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "Audit");
        return resultJson;
    }

    // UnAudit 未审核
    public static JSONObject UnAudit(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("UnAudit", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "UnAudit");
        return resultJson;
    }

    // StatusConvert 状态转换
    public static JSONObject StatusConvert(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("StatusConvert", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "StatusConvert");
        return resultJson;
    }

    // Query 查询
    public static JSONObject Query(String formId, String content, Map<String, Object> dataMap) {
        JSONObject resultJson = handleInvoke("Query", formId, content);
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "Query");
        return resultJson;
    }
}
